package com.example.shipload_e.album_tool;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;

import com.example.shipload_e.R;
import com.example.shipload_e.ShipMentWelcomeActivity;
import com.example.shipload_e.activitys.discharge_feedback.DischargeFinishFormActivity;
import com.example.shipload_e.activitys.shipment_feedback.ShipmentFinishFormActivity;
import com.example.shipload_e.database_dao.DBUtil;
import com.example.shipload_e.service.BizNetworkService;
import com.example.shipload_e.util.HttpActConstant;
import com.example.shipload_e.util.HttpConstant;
import com.example.shipload_e.util.SharePreferenceUtil;
import com.example.shipload_e.util.SystemDateTools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class PublishedActivity extends Activity {

	private GridView	noScrollgridview;
	private GridAdapter	adapter;
	private TextView	activity_selectimg_send, mBack;
	ProgressDialog	    progressDialog;
	PublishedActivity	THISAC	= PublishedActivity.this;
	private MyHandler	publishedActivityHandlers;
	SharePreferenceUtil	spu;
	private Button	    submitMoreTimeBt;

	static class MyHandler extends Handler {
		WeakReference<PublishedActivity>	tActivity;

		MyHandler(PublishedActivity activity) {
			tActivity = new WeakReference<PublishedActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			PublishedActivity theActivity = tActivity.get();
			Bundle data = msg.getData();
			if(!data.isEmpty()) {
				switch (msg.what) {
					case HttpActConstant.PICTURE_UPLOAD:
						String followPastId = theActivity.spu.getFollowId();

						if(HttpConstant.PHOTO_UPLOAD_FAIL.equals(data.getString("submit_result"))) {
							Toast.makeText(theActivity, "图片上传失败", Toast.LENGTH_SHORT).show();
						}
						if(theActivity.spu.getIsLastIndex()) {
							theActivity.progressDialog.dismiss();
							try {
								String count = DBUtil
								        .selectCountAboutPhotoSubmitFail(theActivity, followPastId);
								if(Integer.parseInt(count) > 0) {
									Toast.makeText(theActivity, "有" + count + "张图片上传失败", Toast.LENGTH_SHORT)
									        .show();
									theActivity.submitMoreTimeBt.setText("重发(" + count + ")");
									theActivity.submitMoreTimeBt.setVisibility(View.VISIBLE);
								} else {
									Toast.makeText(theActivity, "图片上传完成", Toast.LENGTH_SHORT)
									        .show();
									if("DischargeFinishFormActivity".equals(theActivity.spu
									        .getFollowActivityName())) {
										Intent in = new Intent(theActivity, DischargeFinishFormActivity.class);
										in.putExtra("followId", theActivity.spu.getFollowId());
										in.putExtra("followResult", theActivity.spu
										        .getFollowResult());
										in.putExtra("followUnit", theActivity.spu.getFollowUnit());
										in.putExtra("followCount", theActivity.spu.getFollowCount());
										theActivity.startActivity(in);
									}
									if("ShipmentFinishFormActivity".equals(theActivity.spu
									        .getFollowActivityName())) {
										Intent in = new Intent(theActivity, ShipmentFinishFormActivity.class);
										in.putExtra("followId", theActivity.spu.getFollowId());
										in.putExtra("followResult", theActivity.spu
										        .getFollowResult());
										in.putExtra("followUnit", theActivity.spu.getFollowUnit());
										in.putExtra("followCount", theActivity.spu.getFollowCount());
										theActivity.startActivity(in);
									} else {
										theActivity
										        .startActivity(new Intent(theActivity, ShipMentWelcomeActivity.class));
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
							theActivity.spu.setIsLastIndex(false);
						}
						break;

					default:
						break;
				}
			} else {}
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_selectimg);
		progressDialog = new ProgressDialog(THISAC);
		spu = new SharePreferenceUtil(THISAC);
		publishedActivityHandlers = new MyHandler(THISAC);
		Init();
		com.example.shipload_e.util.SysApplication.getInstance().addActivity(this);
	}

	public void Init() {
		submitMoreTimeBt = (Button) findViewById(R.id.submit_more_time);
		submitMoreTimeBt.setVisibility(View.GONE);
		mBack = (TextView) findViewById(R.id.m_back);
		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0,View arg1,int arg2,long arg3) {
				if(arg2 == Bimp.bmp.size()) {
					new PopupWindows(PublishedActivity.this, noScrollgridview);
				} else {
					Intent intent = new Intent(PublishedActivity.this, PhotoActivity.class);
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});
		activity_selectimg_send = (TextView) findViewById(R.id.activity_selectimg_send);
		activity_selectimg_send.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				List<String> list = new ArrayList<String>();
				progressDialog.setMessage("图片上传中，请稍候...");
				progressDialog.show();
				for(int i = 0;i < Bimp.drr.size();i++) {
					// if(i == (Bimp.drr.size() - 1)) {
					// spu.setIsLastIndex(true);
					// }
					// String Str = Bimp.drr.get(i)
					// .substring(Bimp.drr.get(i).lastIndexOf("/") + 1, Bimp.drr.get(i)
					// .lastIndexOf("."));
					// list.add(FileUtils.SDPATH + Str + ".JPEG");
					// Map<String, String> params = new HashMap<String, String>();
					// params.put("fpath", Bimp.drr.get(i).toString());
					// new Thread(new BizNetworkService(PublishedActivity.this, handlers,
					// HttpActConstant.PICTURE_UPLOAD, params))
					// .start();
					list.add(Bimp.drr.get(i));
				}
				Map<String, String> params = new HashMap<String, String>();
				params.put("fpathList", list.toString());
				params.put("taskId", spu.getFollowId());
				new Thread(new BizNetworkService(PublishedActivity.this, publishedActivityHandlers, HttpActConstant.PICTURE_UPLOAD, params))
				        .start();
				// 高清的压缩图片全部就在 list 路径里面了
				// 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
				// 完成上传服务器后 .........
				FileUtils.deleteDir();
			}
		});
		mBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if("DischargeFinishFormActivity".equals(spu.getFollowActivityName())) {
					Intent in = new Intent(PublishedActivity.this, DischargeFinishFormActivity.class);
					in.putExtra("followId", spu.getFollowId());
					in.putExtra("followResult", spu.getFollowResult());
					in.putExtra("followUnit", spu.getFollowUnit());
					in.putExtra("followCount", spu.getFollowCount());
					startActivity(in);
				}
				if("ShipmentFinishFormActivity".equals(spu.getFollowActivityName())) {
					Intent in = new Intent(THISAC, ShipmentFinishFormActivity.class);
					in.putExtra("followId", spu.getFollowId());
					in.putExtra("followResult", spu.getFollowResult());
					in.putExtra("followUnit", spu.getFollowUnit());
					in.putExtra("followCount", spu.getFollowCount());
					startActivity(in);
				} else {
					startActivity(new Intent(THISAC, ShipMentWelcomeActivity.class));
				}
			}
		});
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater	inflater;		      // 视图容器
		private int		       selectedPosition	= -1;	// 选中的位置
		private boolean		   shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			return (Bimp.bmp.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position,View convertView,ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if(convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if(position == Bimp.bmp.size()) {
				holder.image.setImageBitmap(BitmapFactory
				        .decodeResource(getResources(), R.drawable.icon_addpic_unfocused));
				if(position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.bmp.get(position));
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView	image;
		}

		Handler	handler	= new Handler() {
			                public void handleMessage(Message msg) {
				                switch (msg.what) {
									case 1:
										adapter.notifyDataSetChanged();
										break;
								}
								super.handleMessage(msg);
							}
		                };

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while(true) {
						if(Bimp.max == Bimp.drr.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							try {
								String path = Bimp.drr.get(Bimp.max);
								String taskId = spu.getFollowId();
								DBUtil.insertIntoPhotos(THISAC, path, taskId, SystemDateTools
								        .getDateByNowByType("yyyy-MM-dd HH:mm:ss"));
								System.out.println(path);
								Bitmap bm = Bimp.revitionImageSize(path);
								Bimp.bmp.add(bm);
								String newStr = path.substring(path.lastIndexOf("/") + 1, path
								        .lastIndexOf("."));
								FileUtils.saveBitmap(bm, "" + newStr);
								Bimp.max += 1;
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
							} catch (IOException e) {

								e.printStackTrace();
							}
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if(s == null)
			return "";
		for(int i = s.length() - 1;i > 0;i++) {
			s.charAt(i);
		}
		return path;
	}

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(PublishedActivity.this, AlbumActivity.class);
					startActivity(intent);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	private static final int	TAKE_PICTURE	= 0x000000;
	private String	         path	         = "";

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System
		        .currentTimeMillis())
		        + ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode,int resultCode,Intent data) {
		switch (requestCode) {
			case TAKE_PICTURE:
				if(Bimp.drr.size() < 9 && resultCode == -1) {
					Bimp.drr.add(path);
				}
				break;
		}
	}

}
